package com.bawei.lib_cache.datastore

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import com.baway.cache.ICache
import com.bawei.lib_base.BaseApp
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking

/**
 * 使用Jetpack组件中的DataStore来实现
 */
object KVDataStore: ICache {
    //使用扩展属性来实现
    private val Context.dataStore:DataStore<Preferences> by preferencesDataStore("video_data_store")

    init {

    }

     fun putString(content:Context, key: String, value: String) {
       BaseApp.appContext.dataStore
    }


    override fun putString( key: String, value: String) {

        //创建协程
        runBlocking {
          val pkay=  stringPreferencesKey(key)
            BaseApp.appContext.dataStore.edit { preference->
              preference[pkay]=value
            }
        }

    }

    override fun putInt(key: String, value: Int) {
        runBlocking {
            val pkay=  intPreferencesKey(key)
            BaseApp.appContext.dataStore.edit { preference->
                preference[pkay]=value
            }
        }
    }

    override fun putLong(key: String, value: Long) {
        runBlocking {
            val pkay=  longPreferencesKey(key)
            BaseApp.appContext.dataStore.edit { preference->
                preference[pkay]=value
            }
        }
    }

    override fun putBool(key: String, value: Boolean) {
        runBlocking {
            val pkay=  booleanPreferencesKey(key)
            BaseApp.appContext.dataStore.edit { preference->
                preference[pkay]=value
            }
        }
    }

    override fun getString(key: String): Flow<String> =BaseApp.appContext.dataStore.data.map { preference-> preference[stringPreferencesKey(key)]!!}

    override fun getInt(key: String): Flow<Int> = BaseApp.appContext.dataStore.data.map { preference-> preference[intPreferencesKey(key)]!!}

    override fun getLong(key: String): Flow<Long> = BaseApp.appContext.dataStore.data.map { preference-> preference[longPreferencesKey(key)]!!}

    override fun getBool(key: String):Flow<Boolean> = BaseApp.appContext.dataStore.data.map { preference-> preference[booleanPreferencesKey(key)]!!}


}